﻿using SharPy.GameSaves;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace SharPy.File_Management
{
    class clFileHelper
    {
        internal static async Task<StorageFile> GetSaveFile(StorageFolder RootFolder)
        {
            StorageFile f;
            try
            {
                f = await RootFolder.GetFileAsync("Save.json");
            }
            catch (FileNotFoundException)
            {
                f = null;
            }
            return f;
        }

        internal static async Task<StorageFile> CreateEmptySaveFile(StorageFolder RootFolder)
        {
            StorageFile f = await RootFolder.CreateFileAsync("Save.json", CreationCollisionOption.ReplaceExisting);

            SaveData list = new SaveData(1, "SaveData");

            SaveDataGroup group = new SaveDataGroup("SaveGroup", "SaveGroup", "Test", "Null", "Null");

            for (int i = 0; i < 12; i++ )
            {
                SaveDataItem it = new SaveDataItem(i, "Save no " + (i + 1).ToString(), 0, "Nothing", "Null", "Fork or spoon?");
                group.Items.Add(it);
            }

            list.Groups.Add(group);

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SaveData));
            Stream str = await f.OpenStreamForWriteAsync();

            ser.WriteObject(str, list);
            str.Dispose();

            return f;
        }

        internal static async Task<int> DeleteGame(string game)
        {
            if (await SharPy.Interface.clDialogs.DeleteGame(game))
            {
                StorageFolder pFolder = await (await ApplicationData.Current.RoamingFolder.GetFolderAsync("Downloads")).GetFolderAsync(game);
                pFolder.DeleteAsync(StorageDeleteOption.PermanentDelete);
                return 1;
            }
            return 0;
        }
    }
}
